import 'dart:async';

import 'package:HealthU/ViewModel/CurrentUserViewModel.dart';
import 'package:HealthU/ViewModel/LoginViewModel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class Index extends StatefulWidget {
  @override
  _IndexState createState() => _IndexState();
}

class _IndexState extends State<Index> {
  List<Widget> pages = [];//声明数组
  int _selectIndex = 0;

  @override
  void initState(){//初始化状态中数组添加4个页面
    pages
      ..add(HomePage())
      ..add(ScalePage())
      ..add(MyPage());
  }

  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text('My TabBar1'),
        backgroundColor: Colors.redAccent, // 设置TabBar的背景颜色
      ),
      body: pages[_selectIndex],//body中展示页面，_selectIndex在点击Item中状态改变进而改变这里

      bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: '我的'),
            BottomNavigationBarItem(icon: Icon(Icons.category), label: "社区"),
            BottomNavigationBarItem(icon: Icon(Icons.settings), label: "发现"),
          ],
          type: BottomNavigationBarType.fixed,
          currentIndex: _selectIndex,
          fixedColor: Colors.redAccent,
          onTap: _onItemTaped
      ),
    );
  }

  _onItemTaped(int index){//点击Item时触发方法改变_selectIndex
    setState(() {
      _selectIndex = index;
    });
  }
}
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('首页'),
    );
  }
}

class ScalePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Consumer(builder: (context, ref, child) {

      final userModel = ref.watch(currentUserModelProvider);

      return Center(
        child: Text(userModel.currentUser != null ? userModel.currentUser!.name:"暂无"),
      );
    });

  }
}

class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {


    return Consumer(

      builder:  (context,ref,child) {

        final viewModel = ref.watch(loginViewModelProvider);


        // final userModel = ref.watch(currentUserModelProvider);
        //
        //
        var futureUser = viewModel.getUserInfo();
        //
        //
        // futureUser.then((user) {
        //   if (user != null) {
        //     // 在这里使用user对象
        //
        //     userModel.setCurrentUser(user!);
        //   } else {
        //     // 处理user为空的情况
        //   }
        // }).catchError((error) {
        //   // 处理错误情况
        // });


        return Center(

            child:ElevatedButton(
              onPressed:() {

                viewModel.logout();

              },
              child:Text('Logout'),
            )

        );


    }

    );

  }
}